#define _GUN_SOURCE //声明可以使用扩展语法
#include <stdio.h>
#include "pthread.h"
#include "unistd.h"
#include "mqueue.h"
#include "string.h"

//路径左侧 / 代表：/dev/mqueue
static char *mq_name = "/mq_test"; 
static mqd_t mq_fd;
void *first_thread_fun(void *arg)
{
    printf("first_thread_fun开始,准备发消息 \n");
    char *msg = "hello";
    mq_send(mq_fd,msg,strlen(msg) + 1,0);
    printf("first_thread_fun 发送消息成功 \n");
    return NULL;
}
void *second_thread_fun(void *arg)
{
    printf("second_thread_fun开始,准备收消息 \n");
    char msg_buf[128];
    ssize_t len = mq_receive(mq_fd,msg_buf,sizeof(msg_buf),NULL);
    
    printf("second_thread_fun 收到消息：%s,长度:%ld \n",msg_buf,len);
    return NULL;
}
int main(int argc, char const *argv[])
{
    //创建消息队列属性结构体
    struct  mq_attr attr;
    attr.mq_maxmsg = 10;  //最大消息数
    attr.mq_msgsize = 128; //消息最大长度

    
   //创建消息队列,可读可写
    mq_fd = mq_open(mq_name,O_CREAT|O_RDWR,0644,&attr);
    if(mq_fd == -1)
    {
        perror("消息队列创建失败");
        return -1;
    }

    pthread_t pt1,pt2;
    pthread_create(&pt1,NULL,first_thread_fun,NULL);
    pthread_create(&pt2,NULL,second_thread_fun,NULL);
    //等待分线程结束
    pthread_join(pt1,NULL);
    pthread_join(pt2,NULL);
    //关闭消息队列
    mq_close(mq_fd);
    //删除消息队列
    mq_unlink(mq_name);
    
    return 0;
}
